package com.ruoyi.resume.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.resume.domain.model.Category;
import com.ruoyi.resume.domain.model.SplitResumeResult;
import com.ruoyi.resume.domain.model.Tag;
import com.ruoyi.resume.domain.request.LabelingRequest;
import com.ruoyi.resume.service.CustomLabelingService;
import com.ruoyi.resume.utils.deepseek.DeepSeekV3Client;
import com.ruoyi.resume.utils.zhipu.Glm;
import com.ruoyi.resume.utils.LabelingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CustomLabelingServiceImpl implements CustomLabelingService {

    @Autowired
    private LabelingUtils labelingUtils;

    @Override
    public List<Map<String, Integer>> generateCustomLabels(LabelingRequest request) {
        // 验证输入是否合法
        validateRequest(request);

        // 获取指定分类的所有标签
        List<Tag> tags = labelingUtils.getTagsByCategoryId(request.getCategory().getId());
        if (tags == null || tags.isEmpty()) {
            return Collections.emptyList();
        }

        // 构建标签描述的完整列表
        String tagDescriptions = tags.stream()
                .map(tag -> String.format("%s(%s)", tag.getTagValue(), tag.getTagDescription()))
                .collect(Collectors.joining(", "));

        // 获取 category.args
        Category category = request.getCategory();
        Map<String, List<String>> args = category.getArgsAsMap();  // 直接使用 getArgsAsMap

        // 提取数据
        SplitResumeResult splitResumeResult = request.getSplitResumeResult();
        System.out.println("获取到的SplitResumeResult: " + JSONObject.toJSONString(splitResumeResult)); // 打印简历内容

        Map<String, Object> extractedData;
        if (args == null || args.isEmpty()) {
            System.out.println("args为空或未定义，直接将SplitResumeResult转换为Map");
            extractedData = JSONObject.parseObject(JSONObject.toJSONString(splitResumeResult), Map.class);
        } else {
            System.out.println("args内容: " + args); // 打印args内容
            extractedData = extractRelevantData(splitResumeResult, args);
        }

// 打印提取到的数据
        System.out.println("提取到的extractedData: " + JSONObject.toJSONString(extractedData));


        // 构建 Prompt
        String prompt = String.format(
                "以下是简历的内容和标签列表，请从中选择最适合简历的标签。只需要返回符合条件的标签值列表，用逗号分隔。如果没有适合的标签，请返回“无”。\n" +
                        "\n标签列表：%s\n\n简历内容：%s",
                tagDescriptions, JSONObject.toJSONString(extractedData)
        );

        // 调用大语言模型
        String result = Glm.chatGLM4(prompt);

        // 解析模型返回结果
        List<String> matchedLabels = parseMatchedLabels(result);

        // 将匹配的标签映射到其对应的tagId
        return mapLabelsToTags(matchedLabels, tags);
    }

    /**
     * 提取 category.args 中定义的字段内容
     */
    private Map<String, Object> extractRelevantData(SplitResumeResult splitResumeResult, Map<String, List<String>> args) {
        Map<String, Object> extractedData = new HashMap<>();
        Map<String, Object> resumeMap = JSONObject.parseObject(JSONObject.toJSONString(splitResumeResult), Map.class);

        for (Map.Entry<String, List<String>> entry : args.entrySet()) {
            String section = entry.getKey();
            List<String> fields = entry.getValue();

            if (!resumeMap.containsKey(section)) {
                continue; // 如果简历里没有这个部分，跳过
            }

            Object sectionData = resumeMap.get(section);
            if (sectionData instanceof List) {
                // 处理列表结构
                List<Map<String, Object>> sectionList = (List<Map<String, Object>>) sectionData;
                List<Map<String, Object>> filteredList = sectionList.stream()
                        .map(item -> filterFields(item, fields))
                        .filter(map -> !map.isEmpty())  // 过滤掉空数据
                        .collect(Collectors.toList());
                extractedData.put(section, filteredList);
            } else if (sectionData instanceof Map) {
                // 处理对象结构
                extractedData.put(section, filterFields((Map<String, Object>) sectionData, fields));
            }
        }
        return extractedData;
    }

    /**
     * 过滤Map中的指定字段
     */
    private Map<String, Object> filterFields(Map<String, Object> data, List<String> fields) {
        Map<String, Object> filteredMap = new HashMap<>();
        for (String field : fields) {
            if (data.containsKey(field)) {
                filteredMap.put(field, data.get(field));
            }
        }
        return filteredMap;
    }

    private void validateRequest(LabelingRequest request) {
        if (request == null || request.getSplitResumeResult() == null || request.getCategory() == null) {
            throw new IllegalArgumentException("请求参数不合法：简历内容或分类信息为空");
        }
    }

    private List<String> parseMatchedLabels(String result) {
        try {
            System.out.println("大语言模型返回结果：" + result);
            if ("无".equals(result.trim())) {
                return Collections.emptyList();
            }
            return Arrays.stream(result.split(","))
                    .map(String::trim)
                    .filter(label -> !label.isEmpty())
                    .collect(Collectors.toList());
        } catch (Exception e) {
            System.err.println("解析返回结果时出错：" + e.getMessage());
            throw new IllegalArgumentException("大语言模型返回的结果格式不正确：" + result, e);
        }
    }

    private List<Map<String, Integer>> mapLabelsToTags(List<String> labels, List<Tag> tags) {
        List<Map<String, Integer>> result = new ArrayList<>();
        for (String label : labels) {
            for (Tag tag : tags) {
                if (label.equals(tag.getTagValue())) {
                    result.add(Collections.singletonMap(label, tag.getId()));
                }
            }
        }
        return result;
    }
}
